<?php

namespace app\api\controller\v25;


use app\api\controller\v2\Auth;
use app\common\cachemodel\AppQq;
use app\common\cachemodel\AppWeibo;
use app\common\cachemodel\FortuneCache;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Wechat;
use app\common\cachemodel\ZlAppleidUser;
use app\common\cachemodel\ZlUserTemporaryTelRecord;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\Aes;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\RecodeCat;
use app\common\model\User;
use app\common\model\UserPush;
use think\Cache;
use think\Db;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

class Info extends Auth
{
    protected $noNeedJudgeSummer = ['香港特别行政区', '澳门特别行政区', '台湾省', '北美洲', '大洋洲', '非洲', '南美洲', '欧洲', '亚洲', ''];

    /**
     * 修改档案出生时间
     * @return Json
     * @throws \Exception
     */
    public function alter_time()
    {
        $year = input('param.year/d');// 出生时间-年
        $month = input('param.month/d');// 出生时间-月
        $uid = $this->user['id'];
        $day = input('param.day/d');// 出生时间-日
        $hour = input('param.hour/d');// 出生时间-时
        $minute = input('param.minute/d');// 出生时间-分
        $timezone = input('param.timezone/d', 8);// 出生时间-时区

        $RecodeModel = new Recode();
        $RecodeCatModel = new RecodeCat();

        // 获取档案信息
        try
        {
            $recode_old = $RecodeModel->getRecodeLists($this->user['id'], 1);
        }
        catch (Exception $e)
        {
            return show(config('code.error'), '获取档案信息失败');
        }

        if (!in_array($recode_old['birth_country'], $this->noNeedJudgeSummer, true))
        {
            $is_summer = isSummerTime($hour, $minute, 0, $month, $day, $year) ? 1 : 0;// 是否开启夏令时
        } else
        {
            $is_summer = 0;
        }

        $data = [
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'hour' => $hour,
            'minute' => $minute,
            'timezone' => $timezone,
            'is_summer' => $is_summer,
        ];
//       检查档案时间格式
        checkRecodeData($year, $month, $day, $hour, $minute, $timezone);

        //获取档案所属档案袋id
        $recode_cat_id = $RecodeCatModel->getRecodeCatId(['uid' => $uid, 'rid' => $recode_old['id']]);

        $longitude = ($recode_old['long_deg'] + $recode_old['long_min'] / 60) * $recode_old['ew'];
        $latitude = ($recode_old['lat_deg'] + $recode_old['lat_min'] / 60) * $recode_old['ns'];
        // 查询当前星盘日月水金火木土等星落座落宫存入数据库
        $astro_data = getTheRecodeAstro($year, $month, $day, $hour, $minute, $longitude, $latitude, $timezone);
        try
        {
            // 更新档案
            $RecodeModel->UpdateData($this->user['id'], $recode_old['id'], array_merge($data, $astro_data));
            Db::table('app_recode_astro')->where(['id' => $recode_old['aid']])->update($astro_data);// 更新档案行星数据
        }
        catch (\Exception $e)
        {
            Log::write('个人中心修改时间失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return show(config('code.error'), '修改信息失败，请稍后再试', []);
        }

        // 档案更新时更新用户档案缓存
        Cache::rm('recode_' . $recode_old['id']);
        // 档案更新时更新用户档案日月升缓存
        Cache::rm('recode_astro_' . $recode_old['id']);
        //删除首页用户星座缓存
        //Cache::rm('d_f_h_sun_in_sign_' . $recode_old['id']);
        FortuneCache::rmFortuneDayCache($recode_old['id'], strtotime(date('Y-m-d') . ' 12:00:00'));

        $array = [
            'id' => $recode_old['id'],
            'cid' => $recode_cat_id,
            'uid' => $recode_old['uid'],
            'aid' => $recode_old['aid'],
            'isself' => $recode_old['isself'],
            'name' => $recode_old['name'],
            'type' => $recode_old['type'],
            'year' => $year,
            'month' => $month,
            'day' => $day,
            'hour' => $hour,
            'minute' => $minute,
            'timezone' => $timezone,
            'birth_country' => $recode_old['birth_country'],
            'birth_province' => $recode_old['birth_province'],
            'birth_city' => $recode_old['birth_city'],
            'live_country' => $recode_old['live_country'],
            'live_province' => $recode_old['live_province'],
            'live_city' => $recode_old['live_city'],
            'status' => $recode_old['status'],
            'comments' => $recode_old['comments'],
            'long_deg' => $recode_old['long_deg'],
            'long_min' => $recode_old['long_min'],
            'ew' => $recode_old['ew'],
            'lat_deg' => $recode_old['lat_deg'],
            'lat_min' => $recode_old['lat_min'],
            'ns' => $recode_old['ns'],
            'is_summer' => $is_summer,
            'avatar' => $recode_old['avatar'],
            'from' => $recode_old['from'] ?? 'zhunle',
        ];
        return show(200, 'ok', array_merge($array, $astro_data));
    }

    /**
     * 个人中心绑定手机号
     * @return Json
     * @throws ApiException
     */
    public function bind_tel()
    {
        //检测用户是否已绑定
        if ($this->user['tel'])
        {
            return show(config('code.error'), '您已绑定手机号');
        }

        $tel = input('param.tel/s', '');
        $code = input('param.code/d', 0);
        $areaCode = input('param.area_code/d', 86);
        $mandatory = input('mandatory/d', 0);
        $mobileTel = $areaCode === 86 ? $tel : $areaCode . '-' . $tel;


        $appConfig = config('app');
        // 短信登录时，检测验证码是否正确
        if (!empty($code))
        {
            if (!in_array($tel, $appConfig['mobile'], false)
                || ($areaCode === 86 && $code != substr($appConfig['code'] * (substr($tel, 3, 6)), 0, 6)))
            {
                //苹果和安卓应用商店审核账号，固定验证码为666666
                if (($tel == '13045794520' && $code == '666666')
                    || ($tel == '13261877781' && $code == '666666'))
                {

                } else
                {
                    //  validate 严格校验
                    $mobileCode = Alidayu::getInstance()->checkSmsIdentify($tel, $areaCode);

                    if ($code != $mobileCode)
                    {
                        return show(config('code.error'), '短信验证码错误');
                    }
                }
            }
        } else
        {
            return show(config('code.error'), '请输入验证码');
        }

        if (!$tel || !$code || strlen($code) != 6)
        {
            return show(config('code.error'), '验证码错误');
        }

        $user = Util::CheckUserTel($tel, $areaCode);

        if (!$mandatory && $user && !empty($user))
        {
            // 判断当前账号是否有订单
            $orderNum = Db::table('wechat_backup_07_18_14_43_00.app_orders')
                ->where(['uid' => $this->user['id'], 'is_del' => 0])
                ->count();

            if ($orderNum)
            {   // 当前账号有订单 旧账号 只能临时绑定
                return show(config('code.success'), '该手机号已被占用', [
                    'type' => 2,
                    'tel_user_name' => $user['nickname']
                ]);
            }

            $recodeNum = Db::table('wechat_backup_07_18_14_43_00.app_recode')->where(['uid' => $this->user['id'], 'status' => 1])->count();

            if ($recodeNum)
            {   // 当前账号有档案 旧账号 只能临时绑定
                return show(config('code.success'), '该手机号已被占用', [
                    'type' => 2,
                    'tel_user_name' => $user['nickname']
                ]);
            }

            // 当前账号没有订单 没有 档案 可以废弃合并到绑定手机号账号
            $wechatModel = new Wechat();
            $qqModel = new AppQq();
            $weiboModel = new AppWeibo();
            $zlAppleidUserModel = new ZlAppleidUser();
            //判断用户是否绑定微信
            $wechatInfo = $wechatModel->where('uid', $this->user['id'])->field('id,unionid')->find();
            if ($wechatInfo)
            {   // 绑定了微信
                // 判断要绑定的手机号账号是否绑定了微信
                $wechatId2 = $wechatModel->where('uid', $user['id'])->value('id');
                if ($wechatId2)
                {
                    $loginToken = md5(uniqid(md5(microtime(true)), true));
                    Cache::set('bindTel:loginToken:' . $mobileTel, $loginToken, 7200);
                    return show(config('code.success'), '绑定失败', [
                        'type' => 3,
                        'tel_user_name' => $user['nickname'],
                        'login_token' => $loginToken
                    ]);
                }
            }
            //判断用户是否绑定了qq
            $qqInfo = $qqModel->where('uid', $this->user['id'])->field('id,unionid')->find();
            if ($qqInfo)
            {   // 绑定了QQ
                // 判断要绑定的手机号账号是否绑定了QQ
                $qqId2 = $qqModel->where('uid', $user['id'])->value('id');
                if ($qqId2)
                {
                    $loginToken = md5(uniqid(md5(microtime(true)), true));
                    Cache::set('bindTel:loginToken:' . $mobileTel, $loginToken, 7200);
                    return show(config('code.success'), '绑定失败', [
                        'type' => 3,
                        'tel_user_name' => $user['nickname'],
                        'login_token' => $loginToken
                    ]);
                }
            }
            //判断用户是否绑定了微博
            $wbInfo = $weiboModel->where('uid', $this->user['id'])->field('id,wbuid')->find();
            if ($wbInfo)
            {   // 绑定了微博
                // 判断要绑定的手机号账号是否绑定了微博
                $wbId2 = $weiboModel->where('uid', $user['id'])->value('id');
                if ($wbId2)
                {
                    $loginToken = md5(uniqid(md5(microtime(true)), true));
                    Cache::set('bindTel:loginToken:' . $mobileTel, $loginToken, 7200);
                    return show(config('code.success'), '绑定失败', [
                        'type' => 3,
                        'tel_user_name' => $user['nickname'],
                        'login_token' => $loginToken
                    ]);
                }
            }
            //判断用户是否绑定了apple
            $appleInfo = $zlAppleidUserModel->where('uid', $this->user['id'])->field('id,apple_id')->find();
            if ($appleInfo)
            {   // 判断要绑定的手机号账号是否绑定了微博
                $appleId2 = $zlAppleidUserModel->where('uid', $user['id'])->value('id');
                if ($appleId2)
                {
                    $loginToken = md5(uniqid(md5(microtime(true)), true));
                    Cache::set('bindTel:loginToken:' . $mobileTel, $loginToken, 7200);
                    return show(config('code.success'), '绑定失败', [
                        'type' => 3,
                        'tel_user_name' => $user['nickname'],
                        'login_token' => $loginToken
                    ]);
                }
            }
            // 开始进行绑定 合并
            $id = (int)($user['id']);
            if ($wechatInfo)
            { // 微信合并
                $wechatModel->where('id', $wechatInfo['id'])->update(['uid' => $id]);
                CacheManage::getInstance()->setCacheConfig('wechat.wechat', $wechatInfo['unionid'] . '-1')->rmCache();
            }
            if ($qqInfo)
            { // QQ合并
                $qqModel->where('id', $qqInfo['id'])->update(['uid' => $id]);
                CacheManage::getInstance()->setCacheConfig('user.qq', $qqInfo['unionid'] . '-1')->rmCache();
            }
            if ($wbInfo)
            { // 微博合并
                $weiboModel->where('id', $wbInfo['id'])->update(['uid' => $id]);
                CacheManage::getInstance()->setCacheConfig('user.weibo', $wbInfo['wbuid'] . '-1')->rmCache();
            }
            if ($appleInfo)
            {   // apple合并
                $zlAppleidUserModel->where('id', $appleInfo['id'])->update(['uid' => $id]);
                CacheManage::getInstance()->setCacheConfig('user.apple', $appleInfo['apple_id'])->rmCache();
            }
            // 使用绑定手机号账号登录
            $token = IAuth::setAppLoginToken($tel); // 生成token
            $data = [
                'token' => $token,
                'token_expire' => strtotime("+" . $appConfig['login_time_out_day'] . " days"),
            ];
            (new User())->save($data, ['id' => $id]);

            $userPush = (new UserPush())->getUserRegid($id);
            $calendarBirthdayStatus = (int)($userPush['calendar_birthday_status'] ?? 0);
            $recodePrivateStatus = (int)($userPush['recode_private_status'] ?? 0);

            if (isset($user['young_pwd']))
            {
                $isYoung = $user['young_pwd'] ? true : false;
            } else
            {
                $isYoung = false;
            }

            $result = [
                'id' => $id,
                'has_self_recode' => $user['has_self_recode'],
                'user_access_token' => (new Aes())->encryptWithOpenssl($token . "||" . $user['id']),
                'uc_id' => $user['uc_id'],
                'calendar_birthday_status' => $calendarBirthdayStatus ?: 1,   // 在天象日历中展示生日信息
                'recode_private_status' => $recodePrivateStatus ?: 1,   // 在星盘中展示档案详细信息
                'has_bind_tel' => 1,     // 是否绑定了手机号 1绑定了 0未绑定
                'is_young_model' => $isYoung ? 1 : 2,
            ];

            return show(config('code.success'), '绑定成功', [
                'type' => 4,
                'access_token_info' => $result
            ]);
        }

        // 若未注册
        try
        {
            // 开始绑定手机号
            if ($mandatory)
            {   // 绑定临时手机号身份凭证
                $bindInfo = [
                    'temporary_tel' => $mobileTel, // 国内手机号不拼接国际手机区号,
                    'tel_bind_time' => $this->request->time()
                ];
            } else
            {
                $bindInfo = ['tel' => $mobileTel, 'temporary_tel' => '', 'tel_bind_time' => 0];
            }
            (new User())->updateUserinfo(['id' => $this->user['id']], $bindInfo);
            (new ZlUserVip())->updateStarNum((int)$this->user['id'], 13); // 绑定手机号任务
            if ($mandatory)
            {   // 记录绑定临时手机号 记录
                (new ZlUserTemporaryTelRecord())->save([
                    'uid' => $this->user['id'],
                    'tel' => $mobileTel,
                    'create_time' => $this->request->time()
                ]);
            }
        }
        catch (\Exception $e)
        {
            Log::write($this->user['id'] . '绑定手机号失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return show(0, '绑定失败');
        }

        $distinctId = $this->request->header('distinct-id', '');
        if ($distinctId)
        {
            //  神策打点 用户绑定手机号时，设置用户属性
            SensorsData::profile($this->user['id'], true, ['user_phone_num' => $mobileTel], 'set');
        }

        return show(config('code.success'), '绑定成功', [
            'type' => 1,
        ]);
    }
}
